﻿#include "tradeservice.h"
#include <QMessageBox>
#include "qrencode.h"

TradeService::TradeService(QObject *parent) : QObject(parent)
{

}

void TradeService::getQrCode(QWidget *widget, QString username, int day, QString totalAmount){
    if(username.isEmpty()){
        QMessageBox::warning(widget, "警告", "用户名不能为空！");
        return;
    }

    if(day<=0){
        QMessageBox::warning(widget, "警告", "续费天数必须大于0！");
        return;
    }

    manager = new TradeNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        Q_UNUSED(message);
        QString qrCode = data.value("qrCode").toString();
        emit this->getQrCodeSuccess(qrCode);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->getQrCode(username, day, totalAmount);
}

void TradeService::queryUserInfo(QWidget *widget, QString username){
    if(username.isEmpty()){
        QMessageBox::warning(widget, "警告", "用户名不能为空！");
        return;
    }

    manager = new TradeNetworkAccessManager();

    connect(manager, &BaseNetworkAccessManager::onSuccessWithData,
            [=](QString message, QJsonObject data)
    {
        Q_UNUSED(message);
        QJsonObject userObj = data.value("query_user").toObject();
        QString companyName;
        if(data.contains("companyName")){
            companyName = data.value("companyName").toString();
        }
        QString serverDate = data.value("server_date").toString();
        bool isValid = (data.value("is_valid").toInt()==1);
        User *user = new User();
        user->loadFromJsonObject(userObj);
        emit this->queryUserInfoSuccess(*user, companyName, serverDate, isValid);
    });

    connect(manager, &BaseNetworkAccessManager::onFailed,
            [=](QString message)
    {
        QMessageBox::warning(widget, "警告", message);
    });

    manager->queryUserInfo(username);
}
